﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GsmComm.GsmCommunication;
using GsmComm.PduConverter;

namespace WebRole1
{
    public partial class About : System.Web.UI.Page
    {
        taraService svc = new taraService();
        public String Send = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                CommSetting.Comm_Port = 6;
                CommSetting.Comm_BaudRate = 9600;
                CommSetting.Comm_TimeOut = 300;

                CommSetting.comm = new GsmComm.GsmCommunication.GsmCommMain(6, 9600, 2000);
                CommSetting.comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
                try
                {
                    CommSetting.comm.Open();
                    //SendMessage(Send, 91151435);
                    lblTest.Text = "";
                }
                catch
                {
                    lblTest.Text = "Please wait for 5 sec and try again";
                }
            }
        }

        private void comm_MessageReceived(object sender, GsmComm.GsmCommunication.MessageReceivedEventArgs e)
        {
            MessageReceived();
        }

        private void MessageReceived()
        {
            string storage = GetMessageStorage();

            DecodedShortMessage[] messages = CommSetting.comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);
            foreach (DecodedShortMessage message in messages)
            {
                Output(string.Format("Message status = {0}, Location = {1}/{2}",
                StatusToString(message.Status), message.Storage, message.Index));
                ShowMessage(message.Data);
                Output("");
            }

            Output(string.Format("{0,9} messages read.", messages.Length.ToString()));
            Output("");
        }
        private string GetMessageStorage()
        {
            string storage = string.Empty;
            storage = PhoneStorageType.Sim;

            if (storage.Length == 0)
                throw new ApplicationException("Unknown message storage.");
            else
                return storage;
        }
        private void Output(string text)
        {
            txtOutput.Text += text;
            txtOutput.Text += "\r\n";
        }
        private string StatusToString(PhoneMessageStatus status)
        {
            // Map a message status to a string
            string ret;
            switch (status)
            {
                case PhoneMessageStatus.All:
                    ret = "All";
                    break;
                case PhoneMessageStatus.ReceivedRead:
                    ret = "Read";
                    break;
                case PhoneMessageStatus.ReceivedUnread:
                    ret = "Unread";
                    break;
                case PhoneMessageStatus.StoredSent:
                    ret = "Sent";
                    break;
                case PhoneMessageStatus.StoredUnsent:
                    ret = "Unsent";
                    break;
                default:
                    ret = "Unknown (" + status.ToString() + ")";
                    break;
            }
            return ret;
        }

        int docHP;
        string orignial;
        string patientName;
        private void ShowMessage(SmsPdu pdu)
        {
            if (pdu is SmsSubmitPdu)
            {
                // Stored (sent/unsent) message
                SmsSubmitPdu data = (SmsSubmitPdu)pdu;
                Output("SENT/UNSENT MESSAGE");
                Output("Recipient: " + data.DestinationAddress);
                Output("Message text: " + data.UserDataText);
                Output("-------------------------------------------------------------------");
                return;
            }
            if (pdu is SmsDeliverPdu)
            {
                // Received message
                SmsDeliverPdu data = (SmsDeliverPdu)pdu;
                Output("RECEIVED MESSAGE");
                Output("Sender: " + data.OriginatingAddress);
                Output("Sent: " + data.SCTimestamp.ToString());
                Output("Message text: " + data.UserDataText);
                Output("-------------------------------------------------------------------");
                orignial = data.OriginatingAddress.Replace("+65", "");
                KeyValuePair<string, string> value = svc.retrieveDoctorNumber(orignial);
                docHP = Convert.ToInt32(value.Value);
                patientName = value.Key;
                Send = "Patient: " + patientName + "," + data.OriginatingAddress;
                Send += "\n" + data.UserDataText;
                return;
            }
            if (pdu is SmsStatusReportPdu)
            {
                // Status report
                SmsStatusReportPdu data = (SmsStatusReportPdu)pdu;
                Output("STATUS REPORT");
                Output("Recipient: " + data.RecipientAddress);
                Output("Status: " + data.Status.ToString());
                Output("Timestamp: " + data.DischargeTime.ToString());
                Output("Message ref: " + data.MessageReference.ToString());
                Output("-------------------------------------------------------------------");
                return;
            }
            Output("Unknown message type: " + pdu.GetType().ToString());
        }

        private void SendMessage(string text, int number)
        {
            try
            {
                // Send an SMS message
                SmsSubmitPdu pdu;

                // The straightforward version
                pdu = new SmsSubmitPdu(text.ToString(), number.ToString(), "");  // "" indicate SMSC No

                // Send the same message multiple times if this is set
                int times = 1;

                // Send the message the specified number of times
                for (int i = 0; i < times; i++)
                {
                    CommSetting.comm.SendMessage(pdu);
                    Output2("Message {0} of {1} sent.", i + 1, times);
                    Output2("");
                }
            }
            catch (Exception ex)
            {
                lblTest.Text = ex.ToString();
            }
        }

        private void Output2(string text, params object[] args)
        {
            string msg = string.Format(text, args);
            Output(msg);
        }
        protected void BtnSMS_Click(object sender, EventArgs e)
        {
            string storage = GetMessageStorage();

            try
            {
                // Read all SMS messages from the storage

                DecodedShortMessage[] messages = CommSetting.comm.ReadMessages(PhoneMessageStatus.All, storage);
                foreach (DecodedShortMessage message in messages)
                {
                    Output(string.Format("Message status = {0}, Location = {1}/{2}",
                    StatusToString(message.Status), message.Storage, message.Index));
                    ShowMessage(message.Data);
                    if (!(message.ToString().Equals("")) && docHP != null)
                        SendMessage(Send, docHP); // contact number need to change
                    CommSetting.comm.DeleteMessage(0, storage);
                    Output("");
                }
                Output(string.Format("{0,9} messages read.", messages.Length.ToString()));
                Output("");
            }
            catch (Exception ex)
            {
                txtOutput.Text = ex.ToString();
            }

            CommSetting.comm.Close();
        }

        protected void BtnRefresh_Click(object sender, EventArgs e)
        {
            txtOutput.Text = "";
            CommSetting.comm.Close();
        }
    }
}